package com.xutianpeng.disk.file.control;

import com.alibaba.fastjson.JSON;
import com.xutianpeng.disk.file.entity.SearchFileEntity;
import com.xutianpeng.disk.file.service.FileIoService;
import com.xutianpeng.disk.file.service.FileService;
import com.xutianpeng.disk.mybatis.entity.PtFileEntity;
import com.xutianpeng.disk.mybatis.flexigrid.PagingEntity;
import com.xutianpeng.disk.mybatis.flexigrid.TblResponseEntity;
import com.xutianpeng.disk.spring.control.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/file")
public class FileController extends BaseController {
    // 日志记录器
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Resource
    private FileService fileService;

    @Resource
    private FileIoService fileIoService;

    // 页面跳转
    @RequestMapping("/fileAll")
    public String fileAll() {
        return "file/filePage";
    }

    // 数据同步
    @RequestMapping("/syncFileData")
    @ResponseBody
    public String syncFileData() {
        try {
            fileIoService.syncFileData();
            return successJson("file.sync.data.success");
        } catch (Exception e) {
            logger.error("文件同步失败", e);
            return failJson("file.sync.data.failed", e.getMessage());
        }
    }

    // 分页查询文件列表
    @RequestMapping("/queryFileInfoListByPage")
    @ResponseBody
    public String queryFileInfoListByPage(SearchFileEntity entity, PagingEntity paging) {
        TblResponseEntity<PtFileEntity> tblResponseEntity = fileService.queryFileInfoListByPage(entity, paging);
        return JSON.toJSONString(tblResponseEntity);
    }

    // 根据ID查询文件信息
    @RequestMapping("/queryFileInfoById")
    @ResponseBody
    public String queryFileInfoById(@RequestParam("fileUuid") String fileUuid) {
        PtFileEntity ptFileEntity = fileService.queryFileInfoById(fileUuid);
        return JSON.toJSONString(ptFileEntity);
    }

    // 创建文件夹
    @RequestMapping("/mkdirFileInfo")
    @ResponseBody
    public String mkdirFileInfo(@RequestParam("parentId") String parentId, @RequestParam("folderName") String folderName) {
        try {
            fileIoService.mkdirFileInfo(parentId, folderName);
            return successJson("file.mkdir.success");
        } catch (Exception e) {
            logger.error("创建文件夹失败", e);
            return failJson("file.mkdir.failed", e.getMessage());
        }
    }

    // 文件上传
    @RequestMapping("/uploadFile")
    @ResponseBody
    public String uploadFile(MultipartHttpServletRequest request, @RequestParam("parentId") String parentId) throws IOException {
        try {
            MultipartFile multipartFile = request.getFile("fileName");
            String fileName = multipartFile.getOriginalFilename();
            fileIoService.uploadFile(parentId, fileName, multipartFile.getInputStream());
            return successJson("file.upload.success");
        } catch (Exception e) {
            logger.error("文件上传失败", e);
            return failJson("file.upload.failed", e.getMessage());
        }
    }

    // 文件移至回收站
    @RequestMapping("/deleteToRecycle")
    @ResponseBody
    public String deleteToRecycle(@RequestParam("fileUuid") String fileUuid) {
        try {
            fileIoService.deleteToRecycle(fileUuid);
            return successJson("file.delete.success");
        } catch (Exception e) {
            logger.error("删除文件到回收站失败，fileUuid: {}", fileUuid, e);
            return failJson("file.delete.failed", e.getMessage());
        }
    }

    // 查询所有文件树
    @RequestMapping("/queryAllFileTree")
    @ResponseBody
    public String queryAllFileTree() {
        List<PtFileEntity> fileTree = fileService.queryAllFileTree();
        return JSON.toJSONString(fileTree);
    }

    // 复制文件
    @RequestMapping("/copyFile")
    @ResponseBody
    public String copyFile(@RequestParam("parentId") String parentId, @RequestParam("srcUuidList") String srcUuidList) {
        try {
            fileIoService.copyFile(parentId, srcUuidList);
            return successJson("file.copy.success");
        } catch (Exception e) {
            logger.error("文件复制失败", e);
            return failJson("file.copy.failed", e.getMessage());
        }
    }

    // 获取分享链接
    @RequestMapping("/getShareUrl")
    @ResponseBody
    public String getShareUrl(@RequestParam("fileUuid") String fileUuid) {
        try {
            String url = fileIoService.getShareUrl(fileUuid);
            return successJson("file.share.success", url);
        } catch (Exception e) {
            logger.error("获取分享链接失败", e);
            return failJson("file.share.failed", e.getMessage());
        }
    }

    // 查询带有效期的分享链接
    @RequestMapping("/queryShareUrl")
    @ResponseBody
    public String queryShareUrl(@RequestParam("fileUuid") String fileUuid, @RequestParam("fileValidity") Integer fileValidity) {
        try {
            String url = fileIoService.queryShareUrl(fileUuid, fileValidity);
            return successJson("file.share.success", url);
        } catch (Exception e) {
            logger.error("查询分享链接失败", e);
            return failJson("file.share.failed", e.getMessage());
        }
    }

    // 移动文件
    @RequestMapping("/moveFiles")
    @ResponseBody
    public String moveFiles(
            @RequestParam("fileUuids") String fileUuids,
            @RequestParam("targetFolderUuid") String targetFolderUuid
    ) {
        try {
            List<String> uuidList = Arrays.asList(fileUuids.split(","));
            fileIoService.moveFiles(uuidList, targetFolderUuid);
            return successJson("file.move.success");
        } catch (Exception e) {
            logger.error("文件移动失败", e);
            return failJson("file.move.fail", e.getMessage());
        }
    }

    // 文件下载
    @RequestMapping("/downFile/{fileUuid}")
    @ResponseBody
    public ResponseEntity<byte[]> downFile(@PathVariable("fileUuid") String fileUuid) {
        return fileIoService.downFile(fileUuid);
    }

    /**
     * 处理文件重命名请求
     * @param fileUuid 要重命名的文件UUID
     * @param newFileName 新的文件名
     * @return 操作结果JSON
     */
    @RequestMapping("/renameFile")
    @ResponseBody
    public String renameFile(
            @RequestParam("fileUuid") String fileUuid,
            @RequestParam("newFileName") String newFileName
    ) {
        try {
            // 调用服务层执行重命名
            String result = fileService.renameFile(fileUuid, newFileName);
            return successJson("file.rename.success", result);
        } catch (IllegalArgumentException e) {
            // 处理参数错误
            return failJson("file.rename.invalid", e.getMessage());
        } catch (Exception e) {
            // 处理其他异常
            logger.error("文件重命名失败", e);
            return failJson("file.rename.fail", e.getMessage());
        }
    }
}